// components/addressPicker/index.js
var service = require('../../service/port')
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    proviceList: [],
    cityList: [],
    areaList: [],

    proviceValue: [0],
    cityValue: [0],
    areaValue: [0]
  },
  attached() {
    this.initData()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    initData(id, callback) {
      //获取省
      this.getAddresList(1, (proviceList) => {
        this.setData({
          proviceList: proviceList
        })
        //获取市
        let defaultProviceId = proviceList[this.data.proviceValue].id
        this.getAddresList(defaultProviceId, (cityList) => {
          this.setData({
            cityList: cityList
          })
          //获取区
          let defaultCityId = cityList[this.data.cityValue].id
          this.getAddresList(defaultCityId, (areaList) => {
            this.setData({
              areaList: areaList
            })
          })
        })
      })
    },

    onConfirm() {
      let proviceList = this.data.proviceList
      let cityList = this.data.cityList
      let areaList = this.data.areaList


      let proviceIndex = this.data.proviceValue[0]
      let cityIndex = this.data.cityValue[0]
      let areaIndex = this.data.areaValue[0]

      let ids = [
        proviceList[proviceIndex] || {},
        cityList[cityIndex] || {},
        areaList[areaIndex] || {}
      ]

      this.triggerEvent('submit', ids);
    },

    onCancel () {
      this.triggerEvent('cancel');
    },

    getAddresList(id, callback) {
      if (!id) return;
      service.getAreaList(id, ({
        data
      }) => {
        if (callback) callback(data)
      })
    },
    onProviceChange(e) {
      let index = e.detail.value

      this.setData({
        proviceValue: index,
        cityValue: [0],
        areaValue: [0],
        cityList: [],
        areaList: [],
      })

      let proviceId = this.data.proviceList[index[0]].id
      this.getAddresList(proviceId, (list) => {
        this.setData({
          cityList: list
        })
        //获取区
        let defaultCityId = list[this.data.cityValue].id
        this.getAddresList(defaultCityId, (areaList) => {
          this.setData({
            areaList: areaList
          })
        })
      })
    },

    onCityChange(e) {
      let index = e.detail.value

      this.setData({
        cityValue: index,
        areaValue: [0],
        areaList: [],
      })

      let cityId = this.data.cityList[index[0]].id
      if (!cityId) return;
      this.getAddresList(cityId, (list) => {
        this.setData({
          areaList: list
        })
      })
    },

    onAreaChange(e) {
      let index = e.detail.value
      this.setData({
        areaValue: index,
      })
    }
  }
})